#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import openpyxl

spath = r'C:\Users\xiaoyao\Desktop\04_05.xlsx'
tpath = r'C:\Users\xiaoyao\Desktop\test.xlsx'

swb = openpyxl.load_workbook(spath)
sws = swb['04_05']

twb = openpyxl.load_workbook(tpath)
tws = twb['Sheet1']
t_date_list = list(range(20180620, 20180631))

t_cur_row, t_cur_column = 3, 4
_suse_date = 0
for s_cur_row in range(2, sws.max_row):
    sid = sws.cell(row=s_cur_row, column=1).value
    sbuy_num = sws.cell(row=s_cur_row, column=2).value
    suse_num = sws.cell(row=s_cur_row, column=3).value
    suse_date = sws.cell(row=s_cur_row, column=4).value
    sbuy_date = sws.cell(row=s_cur_row, column=5).value

    if suse_date < _suse_date:
        t_cur_row += 1

    tid = tws.cell(row=t_cur_row, column=1).value
    if tid is None:
        tws.cell(row=t_cur_row, column=1).value = sid
    elif tid is not None and tid != sid:
        raise ValueError('第{0}行已有数据{1}和要写入数据{2}不一致'.format(t_cur_row, tid, sid))

    tbuy_date = tws.cell(row=t_cur_row, column=2).value
    if tbuy_date is None:
        tws.cell(row=t_cur_row, column=2).value = sbuy_date
    elif tbuy_date is not None and tbuy_date != sbuy_date:
        raise ValueError('第{0}行已有数据{1}和要写入数据{2}不一致'.format(t_cur_row, tbuy_date, sbuy_date))

    tbuy_num = tws.cell(row=t_cur_row, column=3).value
    if tbuy_num is None:
        tws.cell(row=t_cur_row, column=3).value = sbuy_num
    elif tbuy_num is not None and tbuy_num != sbuy_num:
        raise ValueError('第{0}行已有数据{1}和要写入数据{2}不一致'.format(t_cur_row, tbuy_num, sbuy_num))

    suse_num_index =  t_date_list.index(suse_date)
    tws.cell(row=t_cur_row, column=suse_num_index + 4).value = suse_num
    _suse_date = suse_date

twb.save(tpath)
